package capricornus.components.tabctrl
{
	import capricornus.components.button.TriggerButton;
	import capricornus.components.hbox.HBox;
	import capricornus.components.singleselectgroup.GroupEvent;
	import capricornus.components.singleselectgroup.SingleSelectGroup;
	import capricornus.components.sprite.AbstractComponent;
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	
	[Event(name="selectChanged", type="capricornus.components.tabctrl.TabEvent")]
	public class TabCtrl extends AbstractComponent
	{
		private var _group:SingleSelectGroup;
		private var _tabContainer:Sprite;
		
		private var _arrTab:Array;
		private var _arrView:Array;
		
		public function TabCtrl()
		{
			super();
			init();
		}
		
		private function init():void
		{
			_tabContainer = new Sprite();
			_tabContainer.mouseEnabled = false;
			addChild( _tabContainer );
			
			_group = new SingleSelectGroup();
			_arrTab = new Array();
			_arrView = new Array();
			_group.addEventListener( GroupEvent.SELECTED_CHANGE, onSelectChange );
		}
		
		public function addTab( tabName:String, view:Sprite, tabWidth:int=0, tabHeight:int=20, index:int=-1 ):void
		{
			var btn:TriggerButton = new TriggerButton();
			if( tabWidth != 0 )
			{
				btn.setSize( tabWidth, tabHeight );
			}
			else
			{
				btn.autoSize();
			}
			btn.label = tabName;
			if( index==-1 )
			{
				_arrTab.push( btn );
				_arrView.push( view );
			}
			else
			{
				_arrTab.splice( index, 0, btn );
				_arrView.splice( index, 0, view );
			}
			var w:int = 0;
			for( var i:int=0; i<_arrTab.length; i++ )
			{
				var dis:DisplayObject = _arrTab[i];
				if( dis != null )
				{
					_tabContainer.addChild( dis );
					dis.x = w;
					w += dis.width;
				}
			}
			_group.addItem( btn );
		}
		
		private function onSelectChange( e:GroupEvent ):void
		{
			var index:int = _arrTab.indexOf(_group.selectedItem );
			if( index==-1 ) return;
			_tabContainer.setChildIndex( _group.selectedItem, _tabContainer.numChildren-1 );
			
			var view:Sprite = _arrView[index];
			while( _container.numChildren > 0 ) _container.removeChildAt(0);
			if( view != null )
			{
				_container.addChild( view );	
			}
			
			dispatchEvent( new TabEvent( TabEvent.SELECT_CHANGED, index ) );
		}
	}
}